<template>
    <div class="content-filter">
        <!-- 筛选标签栏 -->
        <div class="filter-tabs">
            <van-tabs v-model:active="activeTab" @change="handleTabChange">
                <van-tab title="All" name="all" />
                <van-tab title="Shares" name="shares" />
                <van-tab title="Help" name="help" />
                <van-tab title="Following" name="following" />
            </van-tabs>
        </div>

        <!-- 排序和筛选按钮 -->
        <div class="filter-controls">
            <div class="sort-options">
                <van-dropdown-menu>
                    <van-dropdown-item v-model="sortBy" :options="sortOptions" @change="handleSortChange" />
                </van-dropdown-menu>
            </div>
            <div class="filter-actions">
                <van-button size="small" @click="showFilterPopup">
                    <van-icon name="filter-o" />
                    Filter
                </van-button>
                <van-button size="small" @click="showSearchPopup">
                    <van-icon name="search" />
                </van-button>
            </div>
        </div>

        <!-- 活跃筛选标签 -->
        <div class="active-filters" v-if="activeFilters.length > 0">
            <van-tag v-for="filter in activeFilters" :key="filter.key" closeable type="primary"
                @close="removeFilter(filter.key)">
                {{ filter.label }}
            </van-tag>
            <van-button size="mini" type="default" @click="clearAllFilters">
                Clear All
            </van-button>
        </div>

        <!-- 筛选弹窗 -->
        <van-popup v-model:show="showFilter" position="bottom" :style="{ height: '70%' }" round closeable>
            <div class="filter-popup">
                <div class="popup-header">
                    <h3>Filter Content</h3>
                </div>

                <div class="filter-content">
                    <!-- 内容类型 -->
                    <div class="filter-group">
                        <h4>Content Type</h4>
                        <van-checkbox-group v-model="filterOptions.contentType">
                            <van-checkbox name="experience">Experience Sharing</van-checkbox>
                            <van-checkbox name="tips">Tips & Tricks</van-checkbox>
                            <van-checkbox name="question">Questions</van-checkbox>
                            <van-checkbox name="discussion">Discussions</van-checkbox>
                        </van-checkbox-group>
                    </div>

                    <!-- 难度级别 -->
                    <div class="filter-group">
                        <h4>Difficulty Level</h4>
                        <van-checkbox-group v-model="filterOptions.difficulty">
                            <van-checkbox name="beginner">Beginner</van-checkbox>
                            <van-checkbox name="intermediate">Intermediate</van-checkbox>
                            <van-checkbox name="advanced">Advanced</van-checkbox>
                        </van-checkbox-group>
                    </div>

                    <!-- 话题标签 -->
                    <div class="filter-group">
                        <h4>Topics</h4>
                        <van-checkbox-group v-model="filterOptions.topics">
                            <van-checkbox name="workplace">Workplace</van-checkbox>
                            <van-checkbox name="social">Social Skills</van-checkbox>
                            <van-checkbox name="interview">Interview</van-checkbox>
                            <van-checkbox name="presentation">Presentation</van-checkbox>
                            <van-checkbox name="networking">Networking</van-checkbox>
                            <van-checkbox name="conflict">Conflict Resolution</van-checkbox>
                        </van-checkbox-group>
                    </div>

                    <!-- 时间范围 -->
                    <div class="filter-group">
                        <h4>Time Range</h4>
                        <van-radio-group v-model="filterOptions.timeRange">
                            <van-radio name="today">Today</van-radio>
                            <van-radio name="week">This Week</van-radio>
                            <van-radio name="month">This Month</van-radio>
                            <van-radio name="all">All Time</van-radio>
                        </van-radio-group>
                    </div>

                    <!-- 其他选项 -->
                    <div class="filter-group">
                        <h4>Other Options</h4>
                        <van-checkbox v-model="filterOptions.hasImages">With Images</van-checkbox>
                        <van-checkbox v-model="filterOptions.hasReward">With Reward</van-checkbox>
                        <van-checkbox v-model="filterOptions.solved">Solved Questions Only</van-checkbox>
                        <van-checkbox v-model="filterOptions.trending">Trending Content</van-checkbox>
                    </div>
                </div>

                <div class="filter-actions">
                    <van-button block @click="resetFilters">Reset</van-button>
                    <van-button type="primary" block @click="applyFilters">
                        Apply Filters
                    </van-button>
                </div>
            </div>
        </van-popup>

        <!-- 搜索弹窗 -->
        <van-popup v-model:show="showSearch" position="top" :style="{ height: '100%' }" round>
            <div class="search-popup">
                <div class="search-header">
                    <van-search v-model="searchQuery" placeholder="Search content..." autofocus @search="handleSearch"
                        @cancel="showSearch = false" show-action />
                </div>

                <div class="search-content" v-if="searchQuery.trim()">
                    <!-- 搜索建议 -->
                    <div class="search-suggestions" v-if="searchSuggestions.length > 0">
                        <h4>Suggestions</h4>
                        <div class="suggestion-list">
                            <div v-for="suggestion in searchSuggestions" :key="suggestion" class="suggestion-item"
                                @click="selectSuggestion(suggestion)">
                                <van-icon name="search" />
                                <span>{{ suggestion }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- 热门搜索 -->
                    <div class="popular-searches" v-else>
                        <h4>Popular Searches</h4>
                        <div class="popular-tags">
                            <van-tag v-for="tag in popularSearches" :key="tag" @click="selectSuggestion(tag)">
                                {{ tag }}
                            </van-tag>
                        </div>
                    </div>
                </div>

                <!-- 搜索历史 -->
                <div class="search-history" v-if="!searchQuery.trim() && searchHistory.length > 0">
                    <div class="history-header">
                        <h4>Recent Searches</h4>
                        <van-button size="mini" @click="clearSearchHistory">Clear</van-button>
                    </div>
                    <div class="history-list">
                        <div v-for="(item, index) in searchHistory" :key="index" class="history-item"
                            @click="selectSuggestion(item)">
                            <van-icon name="clock-o" />
                            <span>{{ item }}</span>
                            <van-icon name="cross" @click.stop="removeFromHistory(index)" />
                        </div>
                    </div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

interface FilterOptions {
    contentType: string[]
    difficulty: string[]
    topics: string[]
    timeRange: string
    hasImages: boolean
    hasReward: boolean
    solved: boolean
    trending: boolean
}

interface Emits {
    (e: 'filter-change', filters: any): void
    (e: 'search', query: string): void
    (e: 'tab-change', tab: string): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const activeTab = ref('all')
const sortBy = ref('latest')
const showFilter = ref(false)
const showSearch = ref(false)
const searchQuery = ref('')

const filterOptions = ref<FilterOptions>({
    contentType: [],
    difficulty: [],
    topics: [],
    timeRange: 'all',
    hasImages: false,
    hasReward: false,
    solved: false,
    trending: false
})

const searchHistory = ref<string[]>([
    'workplace communication',
    'interview tips',
    'presentation skills'
])

const sortOptions = [
    { text: 'Latest', value: 'latest' },
    { text: 'Most Popular', value: 'popular' },
    { text: 'Most Helpful', value: 'helpful' },
    { text: 'Most Commented', value: 'commented' }
]

const popularSearches = [
    'workplace', 'interview', 'presentation', 'networking',
    'conflict resolution', 'team communication', 'public speaking'
]

const searchSuggestions = computed(() => {
    if (!searchQuery.value.trim()) return []

    return popularSearches.filter(item =>
        item.toLowerCase().includes(searchQuery.value.toLowerCase())
    ).slice(0, 5)
})

const activeFilters = computed(() => {
    const filters: Array<{ key: string; label: string }> = []

    if (filterOptions.value.contentType.length > 0) {
        filters.push({
            key: 'contentType',
            label: `Type: ${filterOptions.value.contentType.length} selected`
        })
    }

    if (filterOptions.value.difficulty.length > 0) {
        filters.push({
            key: 'difficulty',
            label: `Difficulty: ${filterOptions.value.difficulty.length} selected`
        })
    }

    if (filterOptions.value.topics.length > 0) {
        filters.push({
            key: 'topics',
            label: `Topics: ${filterOptions.value.topics.length} selected`
        })
    }

    if (filterOptions.value.timeRange !== 'all') {
        filters.push({
            key: 'timeRange',
            label: `Time: ${filterOptions.value.timeRange}`
        })
    }

    if (filterOptions.value.hasImages) {
        filters.push({ key: 'hasImages', label: 'With Images' })
    }

    if (filterOptions.value.hasReward) {
        filters.push({ key: 'hasReward', label: 'With Reward' })
    }

    if (filterOptions.value.solved) {
        filters.push({ key: 'solved', label: 'Solved Only' })
    }

    if (filterOptions.value.trending) {
        filters.push({ key: 'trending', label: 'Trending' })
    }

    return filters
})

// 方法
const handleTabChange = (tab: string) => {
    emit('tab-change', tab)
}

const handleSortChange = (value: string) => {
    emit('filter-change', { sort: value, ...filterOptions.value })
}

const showFilterPopup = () => {
    showFilter.value = true
}

const showSearchPopup = () => {
    showSearch.value = true
}

const applyFilters = () => {
    showFilter.value = false
    emit('filter-change', { sort: sortBy.value, ...filterOptions.value })
}

const resetFilters = () => {
    filterOptions.value = {
        contentType: [],
        difficulty: [],
        topics: [],
        timeRange: 'all',
        hasImages: false,
        hasReward: false,
        solved: false,
        trending: false
    }
}

const clearAllFilters = () => {
    resetFilters()
    emit('filter-change', { sort: sortBy.value, ...filterOptions.value })
}

const removeFilter = (filterKey: string) => {
    switch (filterKey) {
        case 'contentType':
            filterOptions.value.contentType = []
            break
        case 'difficulty':
            filterOptions.value.difficulty = []
            break
        case 'topics':
            filterOptions.value.topics = []
            break
        case 'timeRange':
            filterOptions.value.timeRange = 'all'
            break
        case 'hasImages':
            filterOptions.value.hasImages = false
            break
        case 'hasReward':
            filterOptions.value.hasReward = false
            break
        case 'solved':
            filterOptions.value.solved = false
            break
        case 'trending':
            filterOptions.value.trending = false
            break
    }
    emit('filter-change', { sort: sortBy.value, ...filterOptions.value })
}

const handleSearch = () => {
    if (searchQuery.value.trim()) {
        // 添加到搜索历史
        const query = searchQuery.value.trim()
        if (!searchHistory.value.includes(query)) {
            searchHistory.value.unshift(query)
            if (searchHistory.value.length > 10) {
                searchHistory.value = searchHistory.value.slice(0, 10)
            }
        }

        emit('search', query)
        showSearch.value = false
    }
}

const selectSuggestion = (suggestion: string) => {
    searchQuery.value = suggestion
    handleSearch()
}

const clearSearchHistory = () => {
    searchHistory.value = []
}

const removeFromHistory = (index: number) => {
    searchHistory.value.splice(index, 1)
}
</script>

<style lang="scss" scoped>
.content-filter {
    background: white;
    border-bottom: 1px solid #ebedf0;

    .filter-tabs {
        :deep(.van-tabs__nav) {
            padding: 0 16px;
        }
    }

    .filter-controls {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;

        .sort-options {
            flex: 1;
            max-width: 150px;

            :deep(.van-dropdown-menu__bar) {
                box-shadow: none;
                border: 1px solid #ebedf0;
                border-radius: 6px;
            }
        }

        .filter-actions {
            display: flex;
            gap: 8px;

            .van-button {
                font-size: 12px;
            }
        }
    }

    .active-filters {
        padding: 8px 16px 12px;
        display: flex;
        gap: 8px;
        align-items: center;
        flex-wrap: wrap;
    }
}

.filter-popup {
    padding: 20px;
    height: 100%;
    display: flex;
    flex-direction: column;

    .popup-header {
        margin-bottom: 20px;

        h3 {
            font-size: 18px;
            color: #323233;
            margin: 0;
            font-weight: 600;
            text-align: center;
        }
    }

    .filter-content {
        flex: 1;
        overflow-y: auto;

        .filter-group {
            margin-bottom: 24px;

            h4 {
                font-size: 16px;
                color: #323233;
                margin: 0 0 12px 0;
                font-weight: 500;
            }

            .van-checkbox,
            .van-radio {
                margin-bottom: 8px;
                display: block;
            }
        }
    }

    .filter-actions {
        display: flex;
        gap: 12px;
        padding-top: 16px;
        border-top: 1px solid #ebedf0;
    }
}

.search-popup {
    height: 100%;
    display: flex;
    flex-direction: column;

    .search-header {
        padding: 16px;
        border-bottom: 1px solid #ebedf0;
    }

    .search-content,
    .search-history {
        flex: 1;
        padding: 16px;
        overflow-y: auto;

        h4 {
            font-size: 16px;
            color: #323233;
            margin: 0 0 12px 0;
            font-weight: 500;
        }

        .suggestion-list,
        .history-list {

            .suggestion-item,
            .history-item {
                display: flex;
                align-items: center;
                gap: 12px;
                padding: 12px;
                border-radius: 8px;
                cursor: pointer;
                transition: background-color 0.3s;

                &:hover {
                    background: #f7f8fa;
                }

                .van-icon {
                    color: #969799;
                    flex-shrink: 0;
                }

                span {
                    flex: 1;
                    font-size: 15px;
                    color: #323233;
                }
            }
        }

        .popular-tags {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;

            .van-tag {
                cursor: pointer;
            }
        }
    }

    .search-history {
        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .van-button {
                font-size: 12px;
            }
        }
    }
}
</style>